package com.example.Holo.uiactivities;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.example.Holo.R;
import com.example.Holo.core.BaseApplication;
import com.example.Holo.library.viewfinder.IViewFinder;
import com.example.Holo.rework.core.Event;
import com.example.Holo.rework.services.interfaces.IEventService;
import com.example.Holo.rework.services.interfaces.IFriendService;
import com.example.Holo.rework.services.interfaces.IServiceFactory;
import com.example.Holo.utils.functions.IIn;
import com.google.common.base.Predicate;

import java.util.ArrayList;
import java.util.List;

import static android.widget.AdapterView.AdapterContextMenuInfo;
import static com.example.Holo.library.viewfinder.ViewFinders.getViewFinder;
import static com.example.Holo.parameters.IntentConstants.COMMENT;
import static com.example.Holo.parameters.IntentConstants.ID;
import static com.example.Holo.parameters.IntentConstants.NAME;
import static com.example.Holo.utils.collections.Sequences.each;
import static com.google.common.collect.Iterables.removeIf;

public class MainActivity extends SherlockActivity {

    private final List<Event> events = new ArrayList<Event>();
    private ArrayAdapter<Event> adapter;
    private IServiceFactory serviceFactory;

    private Event selectedEventByContextMenu;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        final BaseApplication baseApplication = (BaseApplication) getApplicationContext();
        serviceFactory = baseApplication.getServiceFactory();
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        adapter = new ArrayAdapter<Event>(this, android.R.layout.simple_list_item_1, events) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                final UIHolder uiHolder;
                if (convertView == null) {
                    convertView = getLayoutInflater().inflate(R.layout.event_listview_item, parent, false);
                    uiHolder = UIHolder.createUIHolder(convertView);
                    convertView.setTag(uiHolder);
                } else {
                    uiHolder = (UIHolder) convertView.getTag();
                }
                final Event eventEntity = events.get(position);
                uiHolder.provideValues(eventEntity);
                return convertView;
            }
        };
        //initEventsItems();
        final IViewFinder viewFinder = getViewFinder(this);
        final ListView eventsListView = viewFinder.findListView(R.id.events);
        eventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final Event event = events.get(position);
                final Intent intent = new Intent(MainActivity.this, WorkingActivity.class);
                intent.putExtra(NAME, event.name);
                intent.putExtra(ID, event.id);
                startActivity(intent);
            }
        });
        eventsListView.setAdapter(adapter);
        registerForContextMenu(eventsListView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, view, menuInfo);
        final ListView listView = (ListView) view;
        final AdapterContextMenuInfo item = (AdapterContextMenuInfo) menuInfo;
        selectedEventByContextMenu = (Event) listView.getItemAtPosition(item.position);

        final MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.event_list_view_context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(android.view.MenuItem item) {
        final IEventService eventService = serviceFactory.createEventService();
        final IFriendService friendService = serviceFactory.createFriendService();
        eventService.removeEvent(selectedEventByContextMenu.id);
        friendService.removeAllFriends(selectedEventByContextMenu.id);
        removeIf(events, new Predicate<Event>() {
            @Override
            public boolean apply(Event event) {
                return event.id == selectedEventByContextMenu.id;
            }
        });
        adapter.notifyDataSetChanged();
        return true;
    }

    private void initEventsItems() {
        final IEventService eventService = serviceFactory.createEventService();
        final IFriendService friendService = serviceFactory.createFriendService();
        final List<Event> updatedEvents = each(eventService.getAllEvents(), new IIn<Event>() {
            @Override
            public void in(Event event) {
                event.peopleNumber = friendService.getAllFriends(event.id).size();
            }
        });
        events.clear();
        events.addAll(updatedEvents);
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
        getSupportMenuInflater().inflate(R.menu.activity_menu, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initEventsItems();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_button:
                final Intent intent = new Intent(this, NewEventActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            final IEventService eventService = serviceFactory.createEventService();
            final long addedEventId = eventService.addEvent(createEvent(data));
            final Event event = eventService.getEventById(addedEventId);
            events.add(event);
            adapter.notifyDataSetChanged();
        }
    }

    private Event createEvent(Intent data) {
        final String eventName = data.getStringExtra(NAME);
        final String eventComment = data.getStringExtra(COMMENT);
        return new Event(0, eventName, eventComment);
    }

    private static class UIHolder {

        private final TextView name;
        private final TextView comment;
        private final TextView peopleNumber;

        private UIHolder(TextView name, TextView comment, TextView peopleNumber) {
            this.name = name;
            this.comment = comment;
            this.peopleNumber = peopleNumber;
        }

        public static UIHolder createUIHolder(View view) {
            final IViewFinder viewFinder = getViewFinder(view);
            return new UIHolder(
                    viewFinder.findTextView(R.id.event_listview_item_name),
                    viewFinder.findTextView(R.id.event_listview_item_comment),
                    viewFinder.findTextView(R.id.peopleNumber)
            );
        }

        public void provideValues(Event eventEntity) {
            name.setText(eventEntity.name);
            comment.setText(eventEntity.comment);
            peopleNumber.setText(Integer.toString(eventEntity.peopleNumber));
        }
    }

}
